<template>
	<view class="uni-captcha" :class="{disabled:!isValid}">
	<text class="captcha-text" @click="exec">{{captchaText}}</text>
	</view>
</template>

<script>
	export default {
		name:"uni-captcha",
		data() {
			return {
				captchaText: '',
				running: false
			};
		},
		props: {
			phone:{
			  type:String
			},
			type:{
			  type:String
			},
			text: {
				type: String,
				default: '获取验证码'
			},
			retryText:{
			  type: String,
			  default: '重新获取验证码'
			},
			time: {
				type: Number,
				default: 60
			}
		},
		computed: {
		  /**
		   * 手机号码是否有效
		   * @returns {boolean}
		   */
		  isValid: function(){
			return /^1[3456789]\d{9}$/.test(this.phone);
		  }
		},
		mounted(){
			this.captchaText = this.text;
		},
		methods:{
		  /**
		   * 执行
		   */
		  exec(){
				if(!this.isValid){
					
				  return ;
				}
				if(this.running){
					
					return ;
				}

				this.running = true;
				if(this.interval){
					clearInterval(this.interval);
				}
				
				global.api.appService.sendCaptcha(this.phone, this.type).then((res) => {
					
					var cd = this.time;
					this.interval = setInterval(()=>{
					  cd --;
					  if(cd < 0){
						clearInterval(this.interval);
						this.running = false;
						this.captchaText = this.retryText
						return ;
					  }
					  this.captchaText = cd + 's 后重新获取'
					}, 1000);
					this.captchaText = this.time + 's 后重新获取'
					this.$emit('exec');
				}).catch((err) => {
					this.running = false;
				});

			}
		}
	}
</script>

<style lang="scss">
	.uni-captcha{
		
	}
	
	 .uni-captcha .captcha-text{
		color: $uni-color-primary;
		font-size: 28rpx;
		
	}
	.uni-captcha.disabled .captcha-text{
	  color:#DDDDDD;
	
	}
</style>
